<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/12/2
 * Time: 11:15
 */

namespace pay;

require_once(EXTEND_PATH . 'Paypal/autoload.php');

// 鉴权
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
// 退款
use PayPal\Api\Amount;
use PayPal\Api\Refund;
use PayPal\Api\Sale;
use PayPal\Api\Payment;

class Paypal
{
    // 编号
    public $clientId = 'AU4_5qnsQhiWLmIx8ZJBUy9X7md8cBd8a7b7KPKdbjrPpUtEEm9uByTTS2KL1ImYksm_a4qA3Rw-XIBU';
    
    // 秘钥
    public $clientSecret = 'EBdCzCeqEclxKFNux5hJP-PdkcR0vGjKczjTpvWK63qCeXCH54W3Dw-7cOqhC_koX5waf1q2H_Wxb2WI';
    
    public $Paypal;
    
    public function __construct()
    {
        $this->Paypal = new ApiContext(new OAuthTokenCredential($this->clientId, $this->clientSecret));
    }
    
    /**
     * Paypal退款
     * @param $return_price   退款金额
     * @param $return_id      退款ID
     * @return \think\response\Json
     */
    public function returnPrice($return_price, $return_id){
        $this->Paypal->setConfig([
            'mode' => 'sandbox'
        ]);
        $amt = new Amount();
        $amt->setCurrency('USD')->setTotal($return_price);
    
        $refund = new Refund();
        $refund->setAmount($amt);
    
        // 根据$return_id(paymentId)获取sale id
        $payment = Payment::get($return_id, $this->Paypal);
        $transactions = $payment->getTransactions();
        $resources = $transactions[0]->getRelatedResources();//This DOESN'T work for PayPal transactions.
    
        $sale = $resources[0]->getSale();
        $saleID = $sale->getId();
        
        // 用saleID，申请退款
        $sale = new Sale();
        $sale->setId($saleID);
        
        try{
            $refundedSale = $sale->refundSale($refund, $this->Paypal);
            return ['status' => 200, 'msg' => true];
        }catch(\Paypal\Exception\PayPalConnectionException $ex){
            return ['status' => 0, 'msg' => $ex->getMessage()];
        }
    }
}